package org.biao.aliyundns.task;

import com.aliyun.alidns20150109.models.DescribeDomainRecordsResponseBody;
import lombok.extern.slf4j.Slf4j;
import org.biao.aliyundns.service.AliyunDNSService;
import org.biao.aliyundns.util.NetUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.concurrent.TimeUnit;

/**
 * 定时任务：阿里云域名动态解析
 */
@Slf4j
public class DdnsTask {

    @Autowired
    private AliyunDNSService aliyunDNSService;

    @Scheduled(fixedDelay = 10, timeUnit = TimeUnit.SECONDS)
    public void refreshDNS() {
        String publicIP = NetUtils.getPublicIP();
        log.info("公网IP地址：{}", publicIP);
        if(publicIP == null || publicIP.isEmpty()) {
            return ;
        }
        DescribeDomainRecordsResponseBody.DescribeDomainRecordsResponseBodyDomainRecordsRecord record = aliyunDNSService.describeDomainRecord();
        if (!publicIP.equals(record.getValue())) {
            log.warn("公网IP发生变化，原：{}, 现:{}", record.getValue(), publicIP);
            // IP不一致，重新域名解析
            aliyunDNSService.updateDomainRecord(record.getRecordId(), publicIP);
            log.info("域名解析记录修改成功");
        }
    }

}
